/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.socket.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

/**
 *
 * @author CongChinh
 */
//this thread is created for listening..
public class ServerListeningThread extends Thread {
    ServerSocket serverSocket;
    Socket socket;
    Vector socketStore; // luu giu~ cac socket (ma`) da dc tao ra de? ket noi voi tung client
    ServerSide serverSide;
    public ServerListeningThread(ServerSide serverSide, int port) {                
        socketStore = new Vector();
        this.serverSide = serverSide;        
        try {                        
            serverSocket = new ServerSocket(port);
            socket = new Socket();            
        } catch(IOException ioE) {
            ioE.printStackTrace();
        }        
    }
    @Override
    public void run() {
        try {
            while(true) { // TRUE!!!
            //listening..
            socket = serverSocket.accept();
            //create a new thread to communicate with Client..
            new ServerServiceThread(serverSide, socket).start();
            socketStore.add(socket); //luu giu~ socket da tao ra
            }
        } catch(IOException ioE) {
            ioE.printStackTrace();
        }       
    }
    public void stopListening() { //only stop listening
        try {                     
            serverSocket.close();            
        } catch(IOException ioE) {
            ioE.printStackTrace();
        }
    }
    public void stopServer() { //close all connections (with clients) that had been created
        try {
            serverSocket.close(); //stop lisening..
            //close all sockets / stop all connections
            for (int i = 0; i < socketStore.size(); i++) {                
                if ( ((Socket)(socketStore.elementAt(i))).isClosed() != true ) {
                    ((Socket)(socketStore.elementAt(i))).close();
                }
            }
            this.interrupt(); //..
        } catch(IOException ioE) {
            ioE.printStackTrace();
        }
    }
}
